<template>
  <el-card class="header-card-box">
    <div class="header">
      <Describe v-model="values" />
      <div class="action">
        <span v-if="isEditable">
          <el-button type="primary"
                     :loading="sendLoading"
                     @click="handerSubmit">{{ sendLoading ? "提交中 ..." : "提交" }}</el-button>
          <el-button plain
                     :loading="draftLoading"
                     @click="handerDraft">{{ draftLoading ? "保存中 ..." : "保存草稿" }}</el-button>
          <span class="btn-dropdown">
            <el-dropdown trigger="click">
              <el-button plain
                         class="el-dropdown-link">导入/导出</el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item>
                  <UploadQuotation @importData="importData"
                                   @importLoading="importLoading" />
                </el-dropdown-item>
                <el-dropdown-item>
                  <el-button type="text"
                             icon="el-icon-download"
                             @click="download(templateUrl)">下载模板</el-button>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </span>
        </span>
        <span v-if="isAudit">
          <el-button type="primary"
                     :loading="passLoading"
                     icon="el-icon-s-claim"
                     @click="handerPass"> {{ passLoading ? "提交中 ..." : "通过" }}</el-button>
          <el-button icon="el-icon-s-release"
                     @click="handerRefuse">拒绝</el-button>
          <el-button icon="el-icon-edit-outline"
                     @click="handerDiscussPrice">议价</el-button>
        </span>
        <span class="cancel">
          <el-button plain
                     @click="cancel">取消</el-button>
        </span>
      </div>
    </div>
  </el-card>
</template>

<script>
import UploadQuotation from './Upload.vue'
import { mapActions, mapState } from "vuex";
import quotationApi from "@/api/modules/quotation";
import Describe from './Describe.vue'
import { interceptRules } from '../corePage/index'
import { admin } from "@/api"

/* 审核合约状态 */
const AUDIT_STATE = [11, 14]

/* 修改状态 */
const EDITABLE_STATE = [3, 0]

/* 议价状态 */
const DISCUSS_PRICE_STATUS = 8

export default {
  name: 'QuotationHeader',
  components: { Describe, UploadQuotation },
  props: {
    value: {
      type: Object,
      default: () => { }
    },
    fullscreenLoading: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      draftLoading: false,
      sendLoading: false,
      passLoading: false,
      refuseLoading: false,
      timer: null,
      kwargs: {},
      excelTemplates: [],
      templateName: 'ContractImport',
      templateUrl: '/excelTemplate/合约导入.xlsx'
    }
  },
  computed: {
    ...mapState({
      other: (state) => state.quotation.other,
      detailData: (state) => state.quotation.detailData,
      whole: (state) => state.quotation.whole,
      pick: (state) => state.quotation.pick,
      deliver: (state) => state.quotation.deliver,
      load: (state) => state.quotation.load,
      unload: (state) => state.quotation.unload,
      divide: (state) => state.quotation.divide
    }),

    values () {
      return JSON.parse(JSON.stringify(this.value)) || {}
    },
    isAudit () {
      return AUDIT_STATE.includes(this.values?.status)
    },
    isEditable () {
      return !this.values?.status || EDITABLE_STATE.includes(this.values?.status)
    },
    valueFilter () {
      return (value) => {
        if (value?.customerSelect) {
          const { customerSelect, ...args } = value
          return args
        } else {
          return value
        }
      }
    },
    lowerRules () {
      return {
        whole: this.whole,
        pick: this.pick,
        deliver: this.deliver,
        load: this.load,
        unload: this.unload,
        divide: this.divide
      }
    },
    kwargsValues () {
      return Object.assign(this.valueFilter(this.value.templateId ? this.detailData : this.values), this.other)
    },
    templateDownloadUrl () {
      const remoteUrl = this.excelTemplates
        ?.filter(item => item.name === this.templateName)
        ?.[0]?.url;

      return remoteUrl || this.templateUrl;
    },
  },
  created () {
    // console.log('values====>', this.values)
    this.loadTemplates();
  },
  beforeDestroy () {
    this.$once("hook:beforeDestroy", () => clearInterval(this.timer));
  },
  methods: {
    ...mapActions({
      addCustomer: "quotation/addCustomer",     // 发货方保存
      sendCustomer: "quotation/sendCustomer",    // 发送
      addCarrier: "quotation/addCarrier",       // 承运方保存
      updateCustomer: "quotation/updateCustomer", // 发货方更新 
      updateCarrier: "quotation/updateCarrier"    // 承运方更新
    }),
    // 查询模板
    async loadTemplates () {
      const response = await admin.loadExcelTemplates();
      response.data.map(item => {
        if (item.name === this.templateName) {
          this.templateUrl = item.url;
        }
      })
    },
    download (url) {
      let newUrl = url.includes('https') ? url : url.replace('http', 'https')
      window.location.href = newUrl;
    },
    handerSubmit () {
      this.sendLoading = true;
      const isError = interceptRules(this.lowerRules, true)
      if (isError) {
        setTimeout(async () => {
          try {
            this.sendLoading = false;
            if (this.value.templateId) {
              this.kwargs = this.detailData
            } else {
              this.kwargs = this.values
            }
            // this.kwargs = this.detailData
            await this.sendCustomer({ kwargs: Object.assign(this.valueFilter(this.kwargs), this.other) });
            this.$message.success('操作成功');
            this.cancel();
          } catch (error) {
            console.error(error);
          } finally {
            this.sendLoading = false;
          }
        }, 1200);
        return
      }
      this.sendLoading = false;
    },
    async handerDraft () {
      this.draftLoading = true;
      const isError = interceptRules(this.lowerRules, true)
      if (isError) {
        try {
          await new Promise(resolve => setTimeout(resolve, 1200));
          this.draftLoading = false;

          const valueFilterData = this.valueFilter(this.detailData);
          const kwargs = Object.assign(valueFilterData, this.other);

          if (this.value.carrierId && this.value.templateId) {

            await this.updateCarrier({ kwargs });
          } else if (this.value.carrierId && !this.value.templateId) {

            await this.addCarrier({ kwargs: this.kwargsValues });
          } else if (!this.value.carrierId && this.value.templateId) {

            await this.updateCustomer({ kwargs });
          } else {
            await this.addCustomer({ kwargs: this.kwargsValues });
          }

          // if (this.value.carrierId) {
          //   if (this.value.templateId) {
          //     await this.updateCarrier({ kwargs: Object.assign(this.valueFilter(this.detailData), this.other) });
          //   } else {
          //     await this.addCarrier({ kwargs: this.kwargsValues });
          //   }
          // } else {
          //   if (this.value.templateId) {
          //     await this.updateCustomer({ kwargs: Object.assign(this.valueFilter(this.detailData), this.other) });
          //   } else {
          //     await this.addCustomer({ kwargs: this.kwargsValues });
          //   }
          // }
          this.$message.success('操作成功');
          this.cancel();
        } catch (error) {
          console.error('error', error);
        } finally {
          this.draftLoading = false;
        }
        return
      }
      this.draftLoading = false;
    },
    cancel () {
      this.$router.go(-1)
    },
    handerPass () {
      this.$confirm('是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.templateAgree()
      }).catch(() => { });
    },
    handerRefuse () {
      this.$prompt("", '拒绝原因', {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputType: "textarea",
        inputPattern: /^.{1,200}$/,
        inputPlaceholder: `请输入拒绝原因`,
        inputErrorMessage: `拒绝原因不能为空,且不能超过200个字符`
      })
        .then(({ value }) => {
          this.templateRefuse({ templateId: this.values.templateId, value: value })
        })
        .catch(() => { });
    },
    async templateAgree () {
      await quotationApi.templateAgree({ templateId: this.values.templateId })
      this.cancel()
      this.$message.success('操作成功')
    },
    async templateRefuse ({ templateId, value }) {
      let params = {
        templateId: templateId,
        reason: value
      };
      await quotationApi.templateRefuse(params)
      this.cancel()
      this.$message.success('操作成功')
    },
    // 议价
    handerDiscussPrice () {
      // return this.$message('功能开发中')
      this.$router.push({ name: 'newQuotation', query: { status: DISCUSS_PRICE_STATUS } })
      this.$emit('handerDiscussPrice', { status: DISCUSS_PRICE_STATUS, templateId: this.values.templateId })
    },
    importData (value) {
      this.$emit('importData', value)
    },
    importLoading (value) {
      this.$emit('importLoading', value)
    }
  }
}
</script>

<style scoped>
.header-card-box >>> .el-card__body {
  padding: 12px !important;
}
.header {
  /* height: 32px; */
  /* line-height: 32px; */
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.btn-dropdown {
  /* padding: 0 10px; */
  padding-left: 10px;
}
.action {
  /* display: flex; */
  width: 30%;
  text-align: end;
}
.cancel {
  padding-left: 10px;
}
</style>